package com.blackhorse.xml.dao.impl;

import com.blackhorse.domain.QueryVo;
import com.blackhorse.domain.User;
import com.blackhorse.xml.dao.UserDao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

/**
 * 手动写Dao实现类的方法
 */
public class UserDaoImpl implements UserDao {

    SqlSessionFactory sqlSessionFactory;

    //dao初始化需要传入工厂
    public UserDaoImpl(SqlSessionFactory factory) {
        this.sqlSessionFactory = factory;
    }

    //查询所有
    public List<User> findAll() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> users = sqlSession.selectList("com.blackhorse.xml.dao.UserDao.findAll");
        sqlSession.close();
        return users;
    }

    //保存用户
    public void saveUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.insert("com.blackhorse.xml.dao.UserDao.saveUser", user);
        sqlSession.commit();
        sqlSession.close();
    }

    //更新用户
    public void updateUser(User user) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.update("com.blackhorse.xml.dao.UserDao.updateUser", user);
        sqlSession.commit();
        sqlSession.close();
    }

    //删除用户
    public void deleteUserById(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        sqlSession.update("com.blackhorse.xml.dao.UserDao.deleteUserById", id);
        sqlSession.commit();
        sqlSession.close();
    }

    //查找单个用户
    public User findById(int id) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = sqlSession.selectOne("com.blackhorse.xml.dao.UserDao.findById", id);
        sqlSession.close();
        return user;
    }

    //根据名称模糊查询
    public List<User> findByName(String name) {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<User> users = sqlSession.selectList("com.blackhorse.xml.dao.UserDao.findByName", name);
        sqlSession.close();
        return users;
    }

    //使用聚合函数查询
    public int findTotal() {
        SqlSession sqlSession = sqlSessionFactory.openSession();
        int total = sqlSession.selectOne("com.blackhorse.xml.dao.UserDao.findTotal");
        sqlSession.close();
        return total;
    }

}
